import { randomBytes } from "crypto";
import session from "express-session";
import { existsSync, writeFileSync } from "fs-extra";
import { join } from "path";
import { createClient } from "redis";
import RedisStore from "connect-redis";
import { DependencyContainer } from "tsyringe";
import { ROOT } from "./tokens";
import { PgMemoryStore } from "./pgSessionStorage";

let sessionConfig: session.SessionOptions;
export function getSessionConfig(container: DependencyContainer) {
    if (sessionConfig) return sessionConfig;
    const root = container.resolve(ROOT)
    const dataPath = join(root, 'data')
    sessionConfig = {
        secret: randomBytes(32).toString('base64'),
        saveUninitialized: false,
        name: "SESSION",
        resave: true,
    }
    if (existsSync(join(dataPath, 'session.json'))) {
        sessionConfig = require(join(dataPath, 'session.json'))
    } else {
        writeFileSync(join(dataPath, 'session.json'), JSON.stringify(sessionConfig, null, 2))
    }
    sessionConfig.store = new PgMemoryStore(container)
    if (existsSync(join(dataPath, 'plugins/@sker/redis.json'))) {
        const redisConfig = require(join(dataPath, 'plugins/@sker/redis.json'))
        if (redisConfig.host || redisConfig.url) {
            const redisClient = createClient({
                username: redisConfig.username,
                password: redisConfig.password,
                name: 'sker',
                socket: {
                    host: redisConfig.host,
                    port: redisConfig.port
                },
                database: 3
            })
            redisClient.connect().catch(console.error)
            sessionConfig.store = new RedisStore({
                client: redisClient
            })
        }
    }
    return sessionConfig;
}